import axios from 'axios';
import store from 'store';
import router from '@/router';

axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
axios.defaults.timeout = 60000;

let btnLock = false;

// 添加请求拦截器
axios.interceptors.request.use((config) => {
        config.headers['Authorization'] = store.get('token') || '';
        config.url = config.url + '?r=' + Date.parse(new Date());
        return config;
    }, (error) => {
        return Promise.reject(error);
    }
);

// 添加响应拦截器
axios.interceptors.response.use((response) => {
        const { statusCode, data } = response.data;
        switch (statusCode) {
            case 200:
                return response.data;
            default:
                return Promise.reject(data);
        }

    }, (error) => {
    if (error.statusCode === 403) {
        if (!btnLock) {
            btnLock = true;
            store.remove('token');

            setTimeout(() => {
                router.push('/');
                btnLock = false;
            }, 2000);
        }
        return false;
    }
        return Promise.reject(error);
    }
);

export class BaseService {
    request(params = {}) {
        if (this.prefix) {
            params.url = '/' + this.prefix + params.url;
        }
        return axios({ ...params });
    }
    page(params = {}) {
        return this.request({
            url: '/page',
            params: {
                ...params
            }
        });
    }
    list(params = {}) {
        return this.request({
            url: '/list',
            params: {
                ...params
            }
        });
    }
    info(params = {}) {
        return this.request({
            url: '/info',
            params: {
                ...params
            }
        });
    }
    add(params = {}) {
        return this.request({
            url: '/add',
            method: 'POST',
            data: {
                ...params
            }
        });
    }
    update(params = {}) {
        return this.request({
            url: '/update',
            method: 'POST',
            data: {
                ...params
            }
        });
    }
    delete(params = {}) {
        return this.request({
            url: '/delete',
            method: 'POST',
            data: {
                ...params
            }
        });
    }
}

export function Service(value) {
    return function(target) {
        let prefix = '';
        if (value) {
            let type = typeof value;
            if (type === 'object') {
                prefix = value.prefix;
            } else {
                prefix = value;
            }
        }
        target.prototype.prefix = prefix;
    };
}
